package main

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

type Teacher struct {
	gorm.Model
	Name string
}

type Student struct {
	gorm.Model
	Name string
}

func main() {
	dsn := "root:hedaodao@(127.0.0.1:3306)/gorm_class?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		SkipDefaultTransaction: false,
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "m2m_",
			SingularTable: false,
		},
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		panic(err)
	}

	//迁移时，只迁移HeadMaster就会同时创建两个表
	db.AutoMigrate(&Teacher{}, &Student{})

	//
	s1 := Student{
		Model: gorm.Model{
			ID: 1,
		},
		Name: "学生1",
	}
	s2 := Student{
		Model: gorm.Model{
			ID: 2,
		},
		Name: "学生2",
	}
	t1 := Teacher{
		Model: gorm.Model{
			ID: 1,
		},
		Name: "教师1",
	}
	db.Model(&t1).Association("Students").Append(&s1, &s2)

}
